package com.masterclient.app.modules.aftersale;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.bean.aftersale.AfterSaleBean;
import com.eoner.baselibrary.bean.aftersale.RefundBtnBean;
import com.eoner.baselibrary.bean.goods.PromotionBean;
import com.eoner.baselibrary.utils.IntentUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.sobot.SobotManager;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.modules.aftersale.contract.AfterSaleDetailContract;
import com.masterclient.app.modules.aftersale.contract.AfterSaleDetailPresenter;
import com.masterclient.app.modules.goods.ImageGalleryDialog;
import com.masterclient.app.modules.goods.newpage.activity.NewCommodityDetailActivity;
import com.masterclient.app.modules.order.OrderDetailActivity;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.enumtype.SobotChatTitleDisplayMode;
import com.sobot.chat.api.model.Information;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：sean
 * 创建时间：2017/8/2 00:43
 * 功能说明：
 */
@Route(path = AroutePath.AFTERSALE_DETAIL_ACTIVITY)
public class AfterSaleDetailActivity extends BaseActivity<AfterSaleDetailPresenter> implements AfterSaleDetailContract.View{


    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
//    @BindView(R.id.rl_message)
//    RelativeLayout rlMessage;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_sub_time)
    TextView tvSubTime;
    @BindView(R.id.tv_label_title)
    TextView tvLabelTitle;
    @BindView(R.id.tv_label_desc)
    TextView tvLabelDesc;
    @BindView(R.id.iv1)
    ImageView iv1;
    @BindView(R.id.iv2)
    ImageView iv2;
    @BindView(R.id.iv3)
    ImageView iv3;
    @BindView(R.id.iv4)
    ImageView iv4;
    @BindView(R.id.iv5)
    ImageView iv5;
    @BindView(R.id.ll_return_good)
    LinearLayout llReturnGood;
    @BindView(R.id.iv6)
    ImageView iv6;
    @BindView(R.id.iv7)
    ImageView iv7;
    @BindView(R.id.iv8)
    ImageView iv8;
    @BindView(R.id.tv8)
    TextView tv8;
    @BindView(R.id.ll_retrun_money)
    LinearLayout llRetrunMoney;
    @BindView(R.id.tv_aftersale_type)
    TextView tvAftersaleType;
    @BindView(R.id.tv_aftersale_reason)
    TextView tvAftersaleReason;
    @BindView(R.id.tv_aftersale_money)
    TextView tvAftersaleMoney;
    @BindView(R.id.tv_aftersale_integral)
    TextView tvAftersaleIntegral;
    @BindView(R.id.tv_aftersale_id)
    TextView tvAftersaleId;
    @BindView(R.id.tv_aftersale_time)
    TextView tvAftersaleTime;
    @BindView(R.id.ll_operate)
    LinearLayout llOperate;
    @BindView(R.id.ll_desc)
    LinearLayout llDesc;
//    @BindView(R.id.iv_unread)
//    ImageView ivUnread;
    @BindView(R.id.gridLayout)
    GridLayout gridLayout;
    @BindView(R.id.ll_imgs)
    LinearLayout llImgs;
    @BindView(R.id.ll_good)
    LinearLayout llGood;
    @BindView(R.id.button_see_logistics)
    TextView buttonSeeLogistics;
    @BindView(R.id.button_update_logistics)
    TextView buttonUpdateLogistics;
    @BindView(R.id.button_edit_apply)
    TextView buttonEditApply;
    @BindView(R.id.button_cancel_apply)
    TextView buttonCancelApply;
    @BindView(R.id.button_restart_apply)
    TextView buttonRestartApply;
    @BindView(R.id.button_add_logistics)
    TextView buttonAddLogistics;
    @BindView(R.id.ll_button)
    LinearLayout llButton;
    @BindView(R.id.ll_progress)
    LinearLayout llProgress;

    ImageView[] returnGoodImgs, returnMoneyImgs;
    AfterSaleBean.DataBean dataBean;
    String product_id, order_id;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_address_tel)
    TextView tvAddressTel;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.aftersale_detail_tip)
    TextView aftersaleDetailTip;
    @BindView(R.id.swipeLayout)
    SmartRefreshLayout swipeLayout;
    @BindView(R.id.tv_aftersale_moneyfact)
    TextView tvAftersaleMoneyfact;
    @BindView(R.id.tv_aftersale_integralfact)
    TextView tvAftersaleIntegralfact;
    @BindView(R.id.tv_aftersale_shipping)
    TextView tvAftersaleShipping;

    @BindView(R.id.contact_seller)
    TextView contact_seller;
    @BindView(R.id.tv_aftersale_num)
    TextView tvAftersaleNum;
    @BindView(R.id.tv_aftersale_addressuser)
    TextView tvAftersaleAddressuser;
    @BindView(R.id.tv_aftersale_addressphone)
    TextView tvAftersaleAddressphone;
    @BindView(R.id.tv_aftersale_address)
    TextView tvAftersaleAddress;
    @BindView(R.id.ll_bufa_orderno)
    LinearLayout llBufaOrderno;
    @BindView(R.id.tv_bufa_title)
    TextView tvBufaTitle;
    @BindView(R.id.tv_bufa_orderno)
    TextView tvBufaOrderno;
    @BindView(R.id.tv_tag_order_no)
    TextView tvTagOrderno;

    private RxBus rxBus;

    ImageGalleryDialog imageGallery;
    String type;
    String aftersale_id;
    public final static String NEW_AFTERSALE = "new";//是否是新申请售后

    String sh_sobot_app_key = "";
    private String sh_sobot_flow_company_id;
    private String sh_sobot_flow_group_id;
    private String is_combination = "";
    private boolean mStop,isComplete;
    private Observable<Long> observable;
    private Disposable disposable;
    private long amount = 0;
    private ProgressLoginDialog progressLoginDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aftersale_detail);
        ButterKnife.bind(this);
//        tvKefu.setTypeface(iconfont);
        swipeLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        returnGoodImgs = new ImageView[]{iv1, iv2, iv3, iv4, iv5};
        returnMoneyImgs = new ImageView[]{iv6, iv7, iv8};
        tvBufaTitle.setText("补发订单号\u3000\u3000\u3000");
        tvTagOrderno.setText("售后单号\u3000\u3000\u3000\u3000");

        mStop = true;
        isComplete = false;
        product_id = getBundleString("product_id");
        order_id = getBundleString("order_id");
        type = getBundleString("type");

        progressLoginDialog = new ProgressLoginDialog(this);
        rxBus = RxBus.$();
//        rxBus.OnEvent(rxBus.register(Config.MSG_UNREAD), new Consumer<Object>() {
//            @Override
//            public void accept(@NonNull Object o) throws Exception {
//                if (Config.UNREAD > 0) {
//                    ivUnread.setVisibility(View.VISIBLE);
//                } else {
//                    ivUnread.setVisibility(View.INVISIBLE);
//                }
//            }
//        });

        swipeLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@android.support.annotation.NonNull RefreshLayout refreshLayout) {
                if(disposable != null && !disposable.isDisposed()){
                    disposable.dispose();
                }
                mPresenter.getAfterSaleDetail(order_id, product_id);
            }
        });

    }

    @Override
    protected void onResume() {
        llButton.setVisibility(View.GONE);
        mPresenter.getAfterSaleDetail(order_id, product_id);
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if(disposable != null && !disposable.isDisposed()){
            disposable.dispose();
        }
        rxBus.unregister(Config.MSG_UNREAD);
        super.onDestroy();
    }

    @Override
    public void showAfterSaleInfo(AfterSaleBean.DataBean dataBean) {
        swipeLayout.finishRefresh();
        this.dataBean = dataBean;


        sh_sobot_app_key = dataBean.getSh_sobot_app_key();
        sh_sobot_flow_company_id = dataBean.getSh_sobot_flow_company_id();
        sh_sobot_flow_group_id = dataBean.getSh_sobot_flow_group_id();
        is_combination = dataBean.getSh_is_combination();

        String aftersaleDetailTipContent = "";
        if (dataBean.getSh_tip_items() != null && dataBean.getSh_tip_items().size() > 0) {
            aftersaleDetailTipContent = dataBean.getSh_tip_items().get(0).getSh_label_note();
            tvStatus.setText(dataBean.getSh_tip_items().get(0).getSh_label());
            if (TextUtils.isEmpty(dataBean.getSh_tip_items().get(0).getSh_count_down_time())){
                mStop = true;
                tvSubTime.setText(dataBean.getSh_tip_items().get(0).getSh_time());
            }else {
                amount = Long.parseLong(dataBean.getSh_tip_items().get(0).getSh_count_down_time());
                mStop = false;
                if(observable == null || isComplete) {
                    observable = Observable.interval(0, 1, TimeUnit.SECONDS, Schedulers.computation());
                    observable.take(amount > 0 ? amount : 0).observeOn(AndroidSchedulers.mainThread()).takeWhile(new Predicate<Long>() {
                        @Override
                        public boolean test(Long aLong) throws Exception {
                            return !mStop;
                        }
                    }).subscribe(new Observer<Long>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            disposable = d;
                        }

                        @Override
                        public void onNext(Long aLong) {
                            tvSubTime.setText(dataBean.getSh_tip_items().get(0).getSh_time_before_desc() +
                                    TimeUtil.getTimeStringAftersale(amount - aLong) +
                                    dataBean.getSh_tip_items().get(0).getSh_time_after_desc());
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onComplete() {
                            isComplete = true;
                            if (!mStop) {
                                tvSubTime.setText(
                                        dataBean.getSh_tip_items().get(0).getSh_time_before_desc() +
                                                "00时00分00秒" +
                                                dataBean.getSh_tip_items().get(0).getSh_time_after_desc());
                            }else {
                                tvSubTime.setText(dataBean.getSh_tip_items().get(0).getSh_time());
                            }
                        }

                    });
                }
            }
            tvLabelTitle.setText(dataBean.getSh_tip_items().get(0).getSh_label_title());

            if (TextUtils.isEmpty(dataBean.getSh_tip_items().get(0).getSh_label_desc())) {
                llDesc.setVisibility(View.GONE);
            } else {
                tvLabelDesc.setText(dataBean.getSh_tip_items().get(0).getSh_label_desc());
            }

            if (dataBean.getSh_seller_address() == null || TextUtils.isEmpty(dataBean.getSh_seller_address().getSh_address())) {
                llAddress.setVisibility(View.GONE);
            } else {
                llAddress.setVisibility(View.VISIBLE);
                tvAddressName.setText("联系人：" + dataBean.getSh_seller_address().getSh_full_name());
                tvAddressTel.setText(dataBean.getSh_seller_address().getSh_mobile());
                tvAddress.setText(dataBean.getSh_seller_address().getSh_address());
            }

            if (dataBean.getSh_tip_items().get(0).getSh_button() != null) {

                AfterSaleBean.DataBean.ShTipItemsBean.ShButtonBean buttonBean = dataBean.getSh_tip_items().get(0).getSh_button();
                if ("1".equals(buttonBean.getSh_add_ship_btn()) || "1".equals(buttonBean.getSh_apply_btn()) || "1".equals(buttonBean.getSh_cancel_btn())
                        || "1".equals(buttonBean.getSh_edit_btn()) || "1".equals(buttonBean.getSh_edit_ship_btn()) || "1".equals(buttonBean.getSh_ship_view_btn()))
                    llButton.setVisibility(View.VISIBLE);
                buttonEditApply.setVisibility("1".equals(buttonBean.getSh_edit_btn()) ? View.VISIBLE : View.GONE);
                buttonRestartApply.setVisibility("1".equals(buttonBean.getSh_apply_btn()) ? View.VISIBLE : View.GONE);
                buttonCancelApply.setVisibility("1".equals(buttonBean.getSh_cancel_btn()) ? View.VISIBLE : View.GONE);
                buttonAddLogistics.setVisibility("1".equals(buttonBean.getSh_add_ship_btn()) ? View.VISIBLE : View.GONE);
                buttonSeeLogistics.setVisibility("1".equals(buttonBean.getSh_ship_view_btn()) ? View.VISIBLE : View.GONE);
                buttonUpdateLogistics.setVisibility("1".equals(buttonBean.getSh_edit_ship_btn()) ? View.VISIBLE : View.GONE);
            }
        }

        tvAftersaleMoney.setText("退款金额\u3000\u3000\u3000\u3000" + dataBean.getSh_refund_amount());
        tvAftersaleMoneyfact.setVisibility("1".equals(dataBean.getSh_real_show())&&!"2".equals(dataBean.getSh_refund_type())?View.VISIBLE:View.GONE);
        tvAftersaleMoneyfact.setText("实际退款金额\u3000\u3000" +dataBean.getSh_real_refund_amount());
        tvAftersaleIntegral.setVisibility(((!TextUtils.isEmpty(dataBean.getSh_integral())&&!TextUtils.isEmpty(dataBean.getSh_integral_deduction()))
                &&(Long.parseLong(dataBean.getSh_integral())+Long.parseLong(dataBean.getSh_integral_deduction())!=0) ) ? View.VISIBLE : View.GONE);
        tvAftersaleIntegral.setText("退金币\u3000\u3000\u3000\u3000\u3000" + (Long.parseLong(dataBean.getSh_integral())+Long.parseLong(dataBean.getSh_integral_deduction())));
        tvAftersaleIntegralfact.setVisibility((!TextUtils.isEmpty(dataBean.getSh_real_integral())&&!TextUtils.isEmpty(dataBean.getSh_real_integral_deduction())
                &&"1".equals(dataBean.getSh_real_show())&&(Long.parseLong(dataBean.getSh_real_integral())+Long.parseLong(dataBean.getSh_real_integral_deduction())!=0)) ? View.VISIBLE : View.GONE);
        tvAftersaleIntegralfact.setText("实际退金币\u3000\u3000\u3000" + (Long.parseLong(dataBean.getSh_real_integral())+Long.parseLong(dataBean.getSh_real_integral_deduction())));
        if (!TextUtils.isEmpty(dataBean.getSh_shipping_amount()) && Float.parseFloat(dataBean.getSh_shipping_amount())>0){
            tvAftersaleShipping.setText("退快递费\u3000\u3000\u3000\u3000" + dataBean.getSh_shipping_amount());
            tvAftersaleShipping.setVisibility(View.VISIBLE);
        }else {
            tvAftersaleShipping.setVisibility(View.GONE);
        }
        tvAftersaleReason.setText(("2".equals(dataBean.getSh_refund_type())?"补发":"退款")+"原因\u3000\u3000\u3000\u3000" + dataBean.getSh_reason_text());
        aftersale_id = dataBean.getSh_refund_no();
        tvAftersaleId.setText(dataBean.getSh_refund_no());
        tvAftersaleTime.setText("申请时间\u3000\u3000\u3000\u3000" + dataBean.getSh_create_at());

        tvAftersaleType.setText("售后类型\u3000\u3000\u3000\u3000" + dataBean.getSh_refund_type_label());
        tvBufaOrderno.setText(dataBean.getSh_reissue_order_no());
        llBufaOrderno.setVisibility(TextUtils.isEmpty(dataBean.getSh_reissue_order_no())?View.GONE:View.VISIBLE);
        tvAftersaleNum.setVisibility("2".equals(dataBean.getSh_refund_type())?View.VISIBLE:View.GONE);
        tvAftersaleMoney.setVisibility("2".equals(dataBean.getSh_refund_type())?View.GONE:View.VISIBLE);
        tvAftersaleNum.setText("申请补发数量\u3000\u3000" + dataBean.getSh_refund_qty());
        if (dataBean.getSh_order_address() != null) {
            tvAftersaleAddressuser.setVisibility(!TextUtils.isEmpty(dataBean.getSh_order_address().getSh_full_name()) ? View.VISIBLE : View.GONE);
            tvAftersaleAddressphone.setVisibility(!TextUtils.isEmpty(dataBean.getSh_order_address().getSh_mobile()) ? View.VISIBLE : View.GONE);
            tvAftersaleAddress.setVisibility(!TextUtils.isEmpty(dataBean.getSh_order_address().getSh_address()) ? View.VISIBLE : View.GONE);
            tvAftersaleAddressuser.setText("收件人\u3000\u3000\u3000\u3000\u3000" + dataBean.getSh_order_address().getSh_full_name());
            tvAftersaleAddressphone.setText("收件电话\u3000\u3000\u3000\u3000" + dataBean.getSh_order_address().getSh_mobile());
            tvAftersaleAddress.setText("收件地址\u3000\u3000\u3000\u3000" + dataBean.getSh_order_address().getSh_address());
        }

        llGood.removeAllViews();
        if (dataBean.getSh_products() != null && dataBean.getSh_products().size() > 0) {
            for (AfterSaleBean.DataBean.ShProductsBean bean : dataBean.getSh_products()) {


                View view = View.inflate(mContext, R.layout.item_aftersale_goods, null);
                ViewTransformUtil.glideImageView(mContext, bean.getSh_image(), (ImageView) view.findViewById(R.id.iv_good),
                        R.mipmap.defaults, ScreenUtils.dp2px(90), ScreenUtils.dp2px(90));
                ((TextView) view.findViewById(R.id.tv_title)).setText(bean.getSh_name());
                String skus = "";
                List<AfterSaleBean.DataBean.ShProductsBean.ShPropertyBean> sh_property = bean.getSh_property();
                for (AfterSaleBean.DataBean.ShProductsBean.ShPropertyBean propertyBean : sh_property) {
                    skus += ("“" + propertyBean.getSh_alias_name() + "”");
                }
                ((TextView) view.findViewById(R.id.tv_gos_num)).setVisibility(View.INVISIBLE);
                ((TextView) view.findViewById(R.id.tv_return_money)).setVisibility(View.INVISIBLE);
                ((TextView) view.findViewById(R.id.tv_skus)).setText("规格：" + skus);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(mContext, NewCommodityDetailActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getSh_parent_product_id());
                        intent.putExtras(bundle);
                        mContext.startActivity(intent);
                    }
                });


                //赠品列表
                List<PromotionBean> productMessageList = bean.getSh_promotion();
                View cross_border_layout = view.findViewById(R.id.cross_border_layout);
                if(productMessageList != null && productMessageList.size() > 0){
                    cross_border_layout.setVisibility(View.VISIBLE);
                    LinearLayout ll_shop_present_container = (LinearLayout) view.findViewById(R.id.ll_shop_present_container);
                    ll_shop_present_container.removeAllViews();
                    for(PromotionBean promotionProductMessage : productMessageList){
                        View view_present_goods = View.inflate(mContext,R.layout.item_present,null);
                        ImageView ivPresentGood = (ImageView) view_present_goods.findViewById(R.id.iv_good);
                        TextView ivPresentTitle = (TextView) view_present_goods.findViewById(R.id.tv_title);
                        TextView ivPresentSkus = (TextView) view_present_goods.findViewById(R.id.tv_skus);
                        TextView ivPresentPrice = (TextView) view_present_goods.findViewById(R.id.tv_price);
                        TextView ivPresentNum = (TextView) view_present_goods.findViewById(R.id.tv_num);

                        ivPresentTitle.setText(promotionProductMessage.shName);
                        ivPresentNum.setText("×" + promotionProductMessage.shQty);
                        String skuStr = "";
                        for (String sku : promotionProductMessage.shSku) {
                            skuStr = skuStr + sku;
                        }
                        ivPresentSkus.setText("规格：" + skuStr);
                        ivPresentPrice.setText("¥" + promotionProductMessage.shPrice);
                        ViewTransformUtil.glideImageView(mContext, promotionProductMessage.shProductImg, ivPresentGood,
                                R.mipmap.defaults);

                        view_present_goods.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(AfterSaleDetailActivity.this, NewCommodityDetailActivity.class);
                                intent.putExtra("id",promotionProductMessage.shTargetId);
                                startActivity(intent);
                            }
                        });

                        //GlideUtil.displayRoundImage(mContext,productsBean.getSh_image(),imageView,4,R.mipmap.defaults,107,107);
                        ll_shop_present_container.addView(view_present_goods);
                    }
                }else{
                    cross_border_layout.setVisibility(View.GONE);
                }

                llGood.addView(view);
            }
        }

        llReturnGood.setVisibility(View.GONE);
        llRetrunMoney.setVisibility(View.GONE);
        llProgress.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(aftersaleDetailTipContent)) {//"1".equals(dataBean.getSh_status())||"4".equals(dataBean.getSh_status())||"7".equals(dataBean.getSh_status())||"8".equals(dataBean.getSh_status())
            aftersaleDetailTip.setVisibility(View.VISIBLE);
            aftersaleDetailTip.setText(aftersaleDetailTipContent);
        } else {
            aftersaleDetailTip.setVisibility(View.GONE);
        }
        if (!"9".equals(dataBean.getSh_status())) {
            llProgress.setVisibility(View.VISIBLE);
            if ("1".equals(dataBean.getSh_refund_type())) {
//                tvAftersaleType.setText("售后类型\u3000\u3000\u3000\u3000退货退款");
                llReturnGood.setVisibility(View.VISIBLE);
                if (dataBean.getSh_status_progress().size() >= 2) {
                    int index = dataBean.getSh_status_progress().get(0);
                    int type = dataBean.getSh_status_progress().get(1);
                    for (int i = 0; i <= index; i++) {
                        returnGoodImgs[i].setImageResource(R.mipmap.icon_xuanzhong);
                        if (i == index && type == 0) {
                            returnGoodImgs[i].setImageResource(R.mipmap.icon_xuanzhongx);
                        }
                    }
                }
            } else {
//                tvAftersaleType.setText("售后类型\u3000\u3000\u3000\u3000仅退款");
                llRetrunMoney.setVisibility(View.VISIBLE);
                if("2".equals(dataBean.getSh_refund_type())){
                    tv8.setText("售后完成");
                }
                if (dataBean.getSh_status_progress().size() >= 2) {
                    int index = dataBean.getSh_status_progress().get(0);
                    int type = dataBean.getSh_status_progress().get(1);
                    for (int i = 0; i <= index; i++) {
                        returnMoneyImgs[i].setImageResource(R.mipmap.icon_xuanzhong);
                        if (i == index && type == 0) {
                            returnMoneyImgs[i].setImageResource(R.mipmap.icon_xuanzhongx);
                        }
                    }
                }
            }
        }

        if (dataBean.getSh_images() != null && dataBean.getSh_images().size() > 0) {
            gridLayout.removeAllViews();
            for (String url : dataBean.getSh_images()) {
                ImageView imageView = new ImageView(mContext);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

                gridLayout.addView(imageView);
                GridLayout.LayoutParams params = new GridLayout.LayoutParams(new ViewGroup.LayoutParams(ScreenUtils.dp2px(80), ScreenUtils.dp2px(80)));
                params.setMargins(ScreenUtils.dp2px(2), ScreenUtils.dp2px(2), ScreenUtils.dp2px(2), ScreenUtils.dp2px(2));
                imageView.setLayoutParams(params);
                ViewTransformUtil.glideImageView(AfterSaleDetailActivity.this,url,imageView,R.mipmap.defaults);

            }
            gridLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    imageGallery = new ImageGalleryDialog(mContext, dataBean.getSh_images());
                    imageGallery.show();
                }
            });

        } else {
            llImgs.setVisibility(View.GONE);
        }
    }

    @Override
    public void closeAfterSaleSuccess() {
        showToast("已成功撤销申请");
        RxBus.$().post(Config.AFTERSALE_REFRESH);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            if (NEW_AFTERSALE.equals(type)) {
                startActivitry(AfterSaleListActivity.class, null);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void failed(String msg) {
        showToast(msg);
    }

    @OnClick({R.id.copy_address, R.id.ll_bufa_orderno,R.id.tv_copy, R.id.rl_back, R.id.tv_kefu, R.id.tv_progress, R.id.button_add_logistics, R.id.button_cancel_apply
            , R.id.button_edit_apply, R.id.button_restart_apply, R.id.button_see_logistics, R.id.button_update_logistics,R.id.contact_seller})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.copy_address:
                ((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(
                        ClipData.newPlainText(null, dataBean.getSh_seller_address().getSh_address()
                                +"\n"+ dataBean.getSh_seller_address().getSh_full_name()
                                +" "+dataBean.getSh_seller_address().getSh_mobile()));
                showToast("复制成功");
                break;
            case R.id.ll_bufa_orderno:
                if (dataBean != null &&!TextUtils.isEmpty(dataBean.getSh_reissue_order_no())){
                    Intent intent = new Intent(this, OrderDetailActivity.class);
                    intent.putExtra("order_no",dataBean.getSh_reissue_order_no());
                    startActivity(intent);
                }
                break;
            case R.id.tv_copy:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setPrimaryClip(ClipData.newPlainText(null, aftersale_id));
                showToast("已复制到粘贴板");
                break;
            case R.id.rl_back:
                finish();
                if (NEW_AFTERSALE.equals(type)) {
                    startActivitry(AfterSaleListActivity.class, null);
                }
                break;
            case R.id.tv_kefu:
                Information info = SobotManager.getBaseInfo();
                if (dataBean != null) {
                    Map<String, String> customInfo = new HashMap<String, String>();
                    customInfo.put("aftersale_no", dataBean.getSh_refund_no());
                    customInfo.put("aftersale_status", dataBean.getSh_status_progress().get(0) + "");
                    info.setCustomInfo(customInfo);
                    set_order_card(info);
                }
                //SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.ShowFixedText, "售后详情");
                SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.Default, "");
                SobotApi.startSobotChat(AfterSaleDetailActivity.this, info);
                break;
            case R.id.contact_seller:
                if (dataBean.getSh_is_dealer() && dataBean.getSh_dealer_info() != null &&
                        !TextUtils.isEmpty(dataBean.getSh_dealer_info().getSh_mobile())){
                    ConfirmDialog confirmDialog = new ConfirmDialog(mContext,"是否拨打电话",null,dataBean.getSh_dealer_info().getSh_mobile(),"取消","确定","#FF6809");
                    confirmDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                        @Override
                        public void cancel() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void confirm() {
                            IntentUtil.toPhoneApp(mContext,dataBean.getSh_dealer_info().getSh_mobile());
                            confirmDialog.dismiss();
                        }
                    });
                    confirmDialog.show();
                }else {
                    Information info_seller = SobotManager.getBaseInfo();
                    SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.Default, "");
                    if(!TextUtils.isEmpty(sh_sobot_app_key)){
                        info_seller.setAppkey(sh_sobot_app_key);
                        //info_seller.setInitModeType(4);
                        SobotManager.setSobotFlow(mContext,sh_sobot_flow_company_id,sh_sobot_flow_group_id,"0");
                    }
                    if (dataBean != null) {
                        Map<String, String> customInfo = new HashMap<String, String>();
                        customInfo.put("aftersale_no", dataBean.getSh_refund_no());
                        customInfo.put("aftersale_status", dataBean.getSh_status_progress().get(0) + "");
                        info_seller.setCustomInfo(customInfo);
                        set_order_card(info_seller);
                    }
                    SobotApi.startSobotChat(AfterSaleDetailActivity.this, info_seller);
                }
                break;
            case R.id.tv_progress:
                if (dataBean != null && dataBean.getSh_status_progress() != null && dataBean.getSh_status_progress().size() > 1) {
                    Intent intent = new Intent(mContext, ReturnProgressActivity.class);
                    intent.putExtra("list", (Serializable) dataBean.getSh_status_tip());
                    intent.putExtra("state", dataBean.getSh_status_progress().get(1) + "");
                    startActivity(intent);
                }
                break;
            case R.id.button_cancel_apply:
                if (dataBean == null) return;
                ConfirmDialog dialog = new ConfirmDialog(mContext, "确定要撤销售后申请？", "取消", "确定");
                dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                    @Override
                    public void cancel() {
                        dialog.dismiss();
                    }

                    @Override
                    public void confirm() {
                        click_status = 3;
                        progressLoginDialog.show();
                        progressLoginDialog.setDesc("正在加载...");
                        mPresenter.getRefundBtn(dataBean.getSh_id());
                        //mPresenter.closeAfterSale(dataBean.getSh_id());
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case R.id.button_edit_apply:
                click_status = 2;
                progressLoginDialog.show();
                progressLoginDialog.setDesc("正在加载...");
                mPresenter.getRefundBtn(dataBean.getSh_id());
//                if (TextUtils.isEmpty(product_id) || Long.parseLong(product_id) == 0) {
//                    startActivitry(ReturnMoneyActivity.class, new String[][]{{"product_id", product_id}, {"order_id", order_id}, {"update", "1"}});
//                } else {
//                    startActivitry(ChooseAfterSaleActivity.class, new String[][]{{"product_id", product_id}, {"order_id", order_id}, {"update", "1"}});
//                }
                break;
            case R.id.button_restart_apply:
//                if (TextUtils.isEmpty(product_id) || Long.parseLong(product_id) == 0) {
//                    startActivitry(ReturnMoneyActivity.class, new String[][]{{"product_id", product_id}, {"order_id", order_id}, {"update", "1"}});
//                } else {
//                    startActivitry(ChooseAfterSaleActivity.class, new String[][]{{"product_id", product_id}, {"order_id", order_id}, {"update", "1"}});
//                }
                click_status = 4;
                progressLoginDialog.show();
                progressLoginDialog.setDesc("正在加载...");
                mPresenter.getRefundBtn(dataBean.getSh_id());
                break;
            case R.id.button_see_logistics:
                if (dataBean == null) return;
                click_status = 0;
                progressLoginDialog.show();
                progressLoginDialog.setDesc("正在加载...");
                mPresenter.getRefundBtn(dataBean.getSh_id());
                //startActivitry(LogistInfoActivity.class, new String[][]{{"order_id", dataBean.getSh_id()}, {"from", "refund"}});
                break;
            case R.id.button_add_logistics:
                if (dataBean == null) return;
                click_status = 5;
                progressLoginDialog.show();
                progressLoginDialog.setDesc("正在加载...");
                mPresenter.getRefundBtn(dataBean.getSh_id());
                //startActivitry(AddReturnLogistActivity.class, new String[][]{{"refund_id", dataBean.getSh_id()}, {"update", "0"}});
                break;
            case R.id.button_update_logistics:
                if (dataBean == null) return;
                click_status = 1;
                progressLoginDialog.show();
                progressLoginDialog.setDesc("正在加载...");
                mPresenter.getRefundBtn(dataBean.getSh_id());
//                startActivitry(AddReturnLogistActivity.class, new String[][]{{"refund_id", dataBean.getSh_id()},
//                        {"shipment_company", dataBean.getSh_shipment_company()}, {"shipment_code", dataBean.getSh_shipment_code()},
//                        {"track_no", dataBean.getSh_track_no()}, {"update", "1"}});
                break;
        }
    }

    private void set_order_card(Information info) {
        int totalFee = (int) Float.valueOf(dataBean.getSh_refund_amount()).floatValue();
        String productName = "";
        String productImageeUrl = "";
        if(dataBean.getSh_products().size() > 0) {
            productName = dataBean.getSh_products().get(0).getSh_name();
            productImageeUrl = dataBean.getSh_products().get(0).getSh_image();
        }
        SobotManager.setOrderCardInfo(info,dataBean.getSh_refund_no(),dataBean.getSh_status(),totalFee,"" + dataBean.getSh_products().size(),dataBean.getSh_create_at(),productName,productImageeUrl);
    }


    int click_status = 0;//0 查看物流信息 1 修改退货物流 2 修改申请 3 撤销申请 4 重新发起售后 5 填写退货物流

    @Override
    public void showRefundBtn(RefundBtnBean refundBtnBean) {
        progressLoginDialog.dismiss();
        switch (click_status) {
            case 0:
                if ("1".equals(refundBtnBean.getData().getSh_button().getSh_ship_view_btn())) {
                    startActivitry(LogistInfoActivity.class, new String[][]{{"order_id", dataBean.getSh_id()},{"track_no", ""},{"biz_type", "2"}});
                } else {
                    showToast(refundBtnBean.getData().getSh_tips());
                }
                break;
            case 1:
                if ("1".equals(refundBtnBean.getData().getSh_button().getSh_edit_ship_btn())) {
                    startActivitry(AddReturnLogistActivity.class, new String[][]{{"refund_id", dataBean.getSh_id()},
                            {"shipment_company", dataBean.getSh_shipment_company()}, {"shipment_code", dataBean.getSh_shipment_code()},
                            {"track_no", dataBean.getSh_track_no()}, {"update", "1"}});
                } else {
                    showToast(refundBtnBean.getData().getSh_tips());
                }
                break;
            case 2:
                if ("1".equals(refundBtnBean.getData().getSh_button().getSh_edit_btn())) {
                    intentType();
                } else {
                    showToast(refundBtnBean.getData().getSh_tips());
                }
                break;
            case 3:
                if ("1".equals(refundBtnBean.getData().getSh_button().getSh_cancel_btn())) {
                    mPresenter.closeAfterSale(dataBean.getSh_id());
                } else {
                    showToast(refundBtnBean.getData().getSh_tips());
                }
                break;
            case 4:
                if ("1".equals(refundBtnBean.getData().getSh_button().getSh_apply_btn())) {
                    intentType();
                } else {
                    showToast(refundBtnBean.getData().getSh_tips());
                }
                break;
            case 5:
                if ("1".equals(refundBtnBean.getData().getSh_button().getSh_add_ship_btn())) {
                    startActivitry(AddReturnLogistActivity.class, new String[][]{{"refund_id", dataBean.getSh_id()}, {"update", "0"}});
                } else {
                    showToast(refundBtnBean.getData().getSh_tips());
                }
                break;
        }
    }

    private void intentType(){
        List<Integer> refundTypeArr = dataBean.getSh_update_refund_type_arr();
        if (refundTypeArr == null) return;
        if (refundTypeArr.size()==1){
            if (refundTypeArr.get(0) == 0){
                startActivitry(ReturnMoneyActivity.class, new String[][]{{"product_id", product_id}, {"order_id", order_id}, {"update", "1"}});
            }else if (refundTypeArr.get(0) == 2){
                ARouter.getInstance().build(AroutePath.RETURN_REDELIVER_ACTIVITY)
                        .withString("product_id", product_id)
                        .withString("update", "1")
                        .withString("order_id", order_id).navigation();
            }
        }else {
            Intent intent = new Intent(this, ChooseAfterSaleActivity.class);
            intent.putExtra("product_id", product_id);
            intent.putExtra("order_id", order_id);
            intent.putExtra("update", "1");
            intent.putExtra("show_list",(ArrayList<Integer>) refundTypeArr);
            startActivity(intent);
        }
    }

    @Override
    public void getRefundBtnFail(String msg) {
        progressLoginDialog.dismiss();
        showToast(msg);
    }

}
